﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _7DaysToDieTools.Class;
using System.Text.RegularExpressions;
using System.IO;

namespace _7DaysToDieTools
{
    public partial class FormLang : Form
    {
        #region 公共变量
        private List<LangItem> LangItems = new List<LangItem>();
        private List<LangItem> LangItemsF = new List<LangItem>();

        private Dictionary<string, string> LangItemsA147 = new Dictionary<string, string>();
        private Dictionary<string, string> LangItemsA15 = new Dictionary<string, string>();
        #endregion

        #region 初始化
        public FormLang()
        {
            InitializeComponent();
        }
        public FormLang(Form pForm)
        {
            InitializeComponent();
            this.Location = new Point(pForm.Location.X + pForm.Width / 2 - this.Width / 2, pForm.Location.Y + pForm.Height / 2 - this.Height / 2);
        }

        private void FormLang_Load(object sender, EventArgs e)
        {
            //界面状态
            SetStatus(0);
            //列表选择
            lvList.FullRowSelect = true;
        }

        private void FormLang_Shown(object sender, EventArgs e)
        {
            //选择列表
            if (cboxSele.Items.Count > 0)
            {
                cboxSele.SelectedIndex = 0;
            }
            else
            {
                cboxSele.SelectedIndex = -1;
            }
        }
        #endregion

        #region 方法集

        /// <summary>
        /// 设置界面状态
        /// 0：未加载状态
        /// 1：已加载状态
        /// </summary>
        /// <param name="stateCode"></param>
        private void SetStatus(int stateCode)
        {
            if (stateCode == 0)
            {
                //主按钮
                cboxSele.Enabled = true;
                buttLoad.Visible = true;
                buttClose.Visible = false;
                buttSave.Visible = false;
                //过滤
                panelList.Enabled = false;
                //主界面
                panelMain.Enabled = false;
            }
            else if (stateCode == 1)
            {
                //主按钮
                cboxSele.Enabled = false;
                buttLoad.Visible = false;
                buttClose.Visible = true;
                buttSave.Visible = true;
                //过滤
                panelList.Enabled = true;
                //主界面
                panelMain.Enabled = true;

            }
            else
            {

            }
        }

        /// <summary>
        /// 清空过滤
        /// </summary>
        private void ClearFilter()
        {
            tboxFilter.Text = "";
            ckboxHanE.Checked = true;
            ckboxHanD.Checked = true;
        }

        /// <summary>
        /// 检测项是否有更改
        /// </summary>
        /// <returns></returns>
        private bool ItemHaveChange()
        {
            int tmp = 0;
            return ItemHaveChange(out tmp);
        }
        /// <summary>
        /// 检测项是否有更改
        /// </summary>
        /// <param name="index">返回Index</param>
        /// <returns></returns>
        private bool ItemHaveChange(out int index)
        {
            if (string.IsNullOrEmpty(tboxEKey.Text))
            {
                index = -1;
                return false;
            }
            LangItem tmp = GetItem(tboxEKey.Text);
            if (tmp.Key == tboxEKey.Text &&
                tmp.Source == tboxESource.Text &&
                tmp.Context == tboxEContext.Text &&
                tmp.Changes == tboxEChanges.Text &&
                tmp.English == tboxEEnglish.Text &&
                tmp.French == tboxEFrench.Text &&
                tmp.German == tboxEGerman.Text &&
                tmp.Klingon == tboxEKlingon.Text &&
                tmp.Spanish == tboxESpanish.Text)
            {
                index = LangItems.IndexOf(tmp);
                return false;
            }
            else
            {
                index = LangItems.IndexOf(tmp);
                return true;
            }
        }
         
        /// <summary>
        /// 获取指定KEY的列表项实体
        /// </summary>
        /// <param name="Key">Key名称</param>
        /// <returns></returns>
        private LangItem GetItem(string Key)
        {
            if (string.IsNullOrEmpty(Key))
            {
                return null;
            }
            foreach (LangItem item in LangItems)
            {
                if (item.Key == Key)
                {
                    return item;
                }
            }
            return null;
        }

        /// <summary>
        /// 检测字符串是否含有中文
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool HasChinese(string str)
        {
            return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
        }

        /// <summary>
        /// 清除所有文本框文字
        /// </summary>
        private void ClearMessage()
        {
            tboxEKey.Clear();
            tboxESource.Clear();
            tboxEContext.Clear();
            tboxEChanges.Clear();
            tboxEEnglish.Clear();
            tboxEFrench.Clear();
            tboxEGerman.Clear();
            tboxEKlingon.Clear();
            tboxESpanish.Clear();
            //复位ListView的选择
            lvList.SelectedIndices.Clear();
        }

        /// <summary>
        /// 列表过滤方法
        /// </summary>
        private void ListFilter()
        {
            if (ckboxHanE.Checked && ckboxHanD.Checked)
            {
                LangItemsF = LangItems.Where(str => str.Key.ToLower().Contains(tboxFilter.Text.ToLower())).ToList<LangItem>();

            }
            if (ckboxHanE.Checked && !ckboxHanD.Checked)
            {
                LangItemsF = LangItems.Where(str => str.Key.ToLower().Contains(tboxFilter.Text.ToLower()) && HasChinese(str.English)).ToList<LangItem>();
            }
            if (!ckboxHanE.Checked && ckboxHanD.Checked)
            {
                LangItemsF = LangItems.Where(str => str.Key.ToLower().Contains(tboxFilter.Text.ToLower()) && !HasChinese(str.English)).ToList<LangItem>();
            }
            if (!ckboxHanE.Checked && !ckboxHanD.Checked)
            {
                LangItemsF = new List<LangItem>();
            }
            lvList.VirtualListSize = LangItemsF.Count;
        }

        /// <summary>
        /// 把当前信息写入指定列表项的实体值
        /// </summary>
        /// <param name="index"></param>
        private void WriteToLists(int index)
        {
            LangItems[index].Source = tboxESource.Text;
            LangItems[index].Context = tboxEContext.Text;
            LangItems[index].Changes = tboxEChanges.Text;
            LangItems[index].English = tboxEEnglish.Text;
            LangItems[index].German = tboxEGerman.Text;
            LangItems[index].French = tboxEFrench.Text;
            LangItems[index].Klingon = tboxEKlingon.Text;
            LangItems[index].Spanish = tboxESpanish.Text;
        }
        #endregion

        #region 主按钮
        private void buttLoad_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboxSele.SelectedIndex == -1)
                {
                    MessageBox.Show("请选择要加载的文件");
                    return;
                }
                LangItems = LangAction.LoadLangData(Sinfo.Path.Lang + cboxSele.SelectedItem.ToString());
                LangItemsF = LangItems;
                ClearFilter();
                lvList.VirtualListSize = LangItemsF.Count;
                SetStatus(1);
            }
            catch(Exception x)
            {
                MessageBox.Show("加载数据出错：\n" + x.Message, "警告");
                lvList.VirtualListSize = 0;
                SetStatus(0);
            }
        }

        private void buttClose_Click(object sender, EventArgs e)
        {
            ClearFilter();
            ClearMessage();
            lvList.VirtualListSize = 0;
            LangItems.Clear();
            LangItemsF.Clear();
            SetStatus(0);
        }

        private void buttSave_Click(object sender, EventArgs e)
        {
            try
            {
                int tmpInt = 0;
                if (ItemHaveChange(out tmpInt))
                {
                    if (tmpInt != -1)
                    {
                        WriteToLists(tmpInt);
                    }
                }
                FileStream fs = new FileStream(Sinfo.Path.Lang + cboxSele.SelectedItem.ToString(), FileMode.Create);
                StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false));
                //添加第一行的头
                sw.WriteLine(LangItem.GetHeader());
                //添加数据
                for (int i = 0; i < LangItems.Count; i++)
                {
                    sw.WriteLine(LangItems[i].ToStr());
                }
                sw.Close();
                fs.Close();
                ClearMessage();
                LangItems.Clear();
                lvList.VirtualListSize = 0;
                SetStatus(0);
            }
            catch(Exception x)
            {
                MessageBox.Show("保存失败！\n" + x.Message);
            }
        }

        #endregion

        #region 列表事件
        private void lvList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            e.Item = new ListViewItem(LangItemsF[e.ItemIndex].Key);
        }

        private void lvList_Click(object sender, EventArgs e)
        {
            try
            {
                int i = -1;
                if (ItemHaveChange(out i))
                {
                    WriteToLists(i);
                }
                i = lvList.SelectedIndices[0];
                tboxEKey.Text = LangItemsF[i].Key;
                tboxESource.Text = LangItemsF[i].Source;
                tboxEContext.Text = LangItemsF[i].Context;
                tboxEChanges.Text = LangItemsF[i].Changes;
                tboxEEnglish.Text = LangItemsF[i].English;
                tboxEGerman.Text = LangItemsF[i].German;
                tboxEFrench.Text = LangItemsF[i].French;
                tboxEKlingon.Text = LangItemsF[i].Klingon;
                tboxESpanish.Text = LangItemsF[i].Spanish;
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }
        }
        #endregion

        #region 过滤
        private void tboxFilter_TextChanged(object sender, EventArgs e)
        {
            ListFilter();
        }

        private void ckboxHanE_CheckedChanged(object sender, EventArgs e)
        {
            ListFilter();
        }

        private void ckboxHanD_CheckedChanged(object sender, EventArgs e)
        {
            ListFilter();
        }
        private void buttFilter_Click(object sender, EventArgs e)
        {
            ClearFilter();
        }

        #endregion

        #region 项编辑框
        private void tboxESource_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxESource.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxESource.Text = fe.EditString;
            }
        }

        private void tboxEContext_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxEContext.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxEContext.Text = fe.EditString;
            }
        }

        private void tboxEChanges_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxEChanges.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxEChanges.Text = fe.EditString;
            }
        }

        private void tboxEEnglish_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxEEnglish.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxEEnglish.Text = fe.EditString;
            }
        }

        private void tboxEFrench_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxEFrench.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxEFrench.Text = fe.EditString;
            }
        }

        private void tboxEGerman_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxEGerman.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxEGerman.Text = fe.EditString;
            }
        }

        private void tboxEKlingon_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxESpanish.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxESpanish.Text = fe.EditString;
            }
        }

        private void tboxESpanish_DoubleClick(object sender, EventArgs e)
        {
            FormLangEdit fe = new FormLangEdit(this);
            fe.EditString = tboxEContext.Text;
            if (fe.ShowDialog() == DialogResult.OK)
            {
                tboxEContext.Text = fe.EditString;
            }
        }

        private void buttDingWei_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tboxEKey.Text))
            {
                ClearFilter();
                lvList.SelectedIndices.Clear();
                int tmp = LangItems.IndexOf(GetItem(tboxEKey.Text));
                lvList.SelectedIndices.Add(tmp);
                lvList.EnsureVisible(tmp);
                lvList.Focus();
            }
        }

        private void buttCopyKey_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tboxEKey.Text))
            {
                return;
            }
            Clipboard.SetText(tboxEKey.Text);
            
        }

        private void buttC1_Click(object sender, EventArgs e)
        {
            tboxEEnglish.Clear();
        }

        private void buttC2_Click(object sender, EventArgs e)
        {
            tboxEFrench.Clear();
        }

        private void buttC3_Click(object sender, EventArgs e)
        {
            tboxEGerman.Clear();
        }

        private void buttC4_Click(object sender, EventArgs e)
        {
            tboxEKlingon.Clear();
        }

        private void buttC5_Click(object sender, EventArgs e)
        {
            tboxESpanish.Clear();
        }



        #endregion

        #region 加载与替换字段
        private void buttLoadShiftA147_Click(object sender, EventArgs e)
        {
            ofdFile.Filter = "语言文件|" + cboxSele.SelectedItem.ToString();
            ofdFile.FileName = cboxSele.SelectedItem.ToString();
            if (ofdFile.ShowDialog() == DialogResult.OK)
            {
                LangItemsA147.Clear();
                using (CsvFileReader CFR = new CsvFileReader(ofdFile.FileName))
                {
                    CsvRow cr = new CsvRow();
                    if (!CFR.ReadRow(cr))
                    {
                        return;
                    }
                    if (cr.Count != 7)
                    {
                        MessageBox.Show("请选择七日杀A14.7版本的语言文件！");
                        return;
                    }
                    else
                    {
                        LangItemsA147.Add(cr[0], cr[4]);
                    }
                    while (CFR.ReadRow(cr))
                    {
                        LangItemsA147.Add(cr[0], cr[4]);
                    }
                }
                if(MessageBox.Show("已经加载" + LangItemsA147.Count.ToString() + "条记录！\n是否进行替换？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    int JiShu = 0;
                    string tmp = "";
                    foreach (LangItem x in LangItems)
                    {
                        if (LangItemsA147.TryGetValue(x.Key, out tmp))
                        {
                            if (HasChinese(tmp))
                            {
                                if (!HasChinese(x.English))
                                {
                                    x.English = tmp;
                                    JiShu++;
                                }
                            }

                        }
                    }
                    MessageBox.Show("替换完成！总计替换了：" + JiShu.ToString() + "条记录！");
                }
            }
        }

        private void buttLoadShiftA15_Click(object sender, EventArgs e)
        {
            ofdFile.Filter = "语言文件|" + cboxSele.SelectedItem.ToString();
            ofdFile.FileName = cboxSele.SelectedItem.ToString();
            if (ofdFile.ShowDialog() == DialogResult.OK)
            {
                LangItemsA15.Clear();
                using (CsvFileReader CFR = new CsvFileReader(ofdFile.FileName))
                {
                    CsvRow cr = new CsvRow();
                    if (!CFR.ReadRow(cr))
                    {
                        return;
                    }
                    if (cr.Count != 9)
                    {
                        MessageBox.Show("请选择七日杀A15版本的语言文件！");
                        return;
                    }
                    else
                    {
                        LangItemsA15.Add(cr[0], cr[4]);
                    }
                    while (CFR.ReadRow(cr))
                    {
                        LangItemsA15.Add(cr[0], cr[4]);
                    }
                }
                if (MessageBox.Show("已经加载" + LangItemsA15.Count.ToString() + "条记录！\n是否进行替换？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    int JiShu = 0;
                    string tmp = "";
                    foreach (LangItem x in LangItems)
                    {
                        if (LangItemsA15.TryGetValue(x.Key, out tmp))
                        {
                            if (HasChinese(tmp))
                            {
                                if (!HasChinese(x.English))
                                {
                                    x.English = tmp;
                                    JiShu++;
                                }
                            }

                        }
                    }
                    MessageBox.Show("替换完成！总计替换了：" + JiShu.ToString() + "条记录！");
                }
            }
        }
        #endregion

        #region 清空指定语言
        private void buttLangClear_Click(object sender, EventArgs e)
        {
            if (!ckboxLC1.Checked && !ckboxLC2.Checked && !ckboxLC3.Checked && !ckboxLC4.Checked && !ckboxLC5.Checked)
            {
                MessageBox.Show("请选择要清空的语言！");
                return;
            }
            ClearMessage();
            foreach (LangItem item in LangItems)
            {
                if (ckboxLC1.Checked)
                {
                    item.English = "";
                }
                if (ckboxLC2.Checked)
                {
                    item.French = "";
                }
                if (ckboxLC3.Checked)
                {
                    item.German = "";
                }
                if (ckboxLC4.Checked)
                {
                    item.Klingon = "";
                }
                if (ckboxLC5.Checked)
                {
                    item.Spanish = "";
                }
            }
            MessageBox.Show("清空完成！请手动保存文件！");
        }

        #endregion

        #region 添加删除项
        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormLangAdd fla = new FormLangAdd(this);
            if (fla.ShowDialog() == DialogResult.OK)
            {
                //检测是否同名
                foreach (LangItem item in LangItems)
                {
                    if (item.Key == fla.TheAddItem.Key)
                    {
                        MessageBox.Show("检测到名称(Key)相同，请重新输入！");
                        return;
                    }
                }

                ClearMessage();
                LangItems.Add(fla.TheAddItem);
                int tmp = LangItems.IndexOf(fla.TheAddItem);
                ClearFilter();
                lvList.VirtualListSize = tmp + 1;
                lvList.SelectedIndices.Add(tmp);
                lvList.EnsureVisible(tmp);
                lvList.Focus();
                ListFilter();
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lvList.SelectedIndices.Count <= 0)
            {
                MessageBox.Show("请选择要删除的项！", "提示");
                return;
            }

            if (MessageBox.Show("是否确认删除？\n[" + LangItemsF[lvList.SelectedIndices[0]].Key + "]", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                LangItems.Remove(LangItemsF[lvList.SelectedIndices[0]]);
                ClearMessage();
                lvList.VirtualListSize--;
                ListFilter();
            }
        }
        #endregion
    }
}
